from pywinauto import Application, Desktop
from pywinauto.findwindows import ElementNotFoundError
import pyautogui
import time
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'tool'))
from browser_mcp import BrowserMCP


class WindowAgent:
    def __init__(self):
        self.app = None
        self.window = None
        self.browser = None
    
    def connect_app(self, title=None, process=None):
        """连接到已运行的应用程序"""
        try:
            if title:
                self.app = Application(backend="uia").connect(title=title)
            elif process:
                self.app = Application(backend="uia").connect(process=process)
            return True
        except Exception as e:
            print(f"连接失败: {e}")
            return False
    
    def start_app(self, path):
        """启动应用程序"""
        try:
            self.app = Application(backend="uia").start(path)
            return True
        except Exception as e:
            print(f"启动失败: {e}")
            return False
    
    def get_window(self, title):
        """获取窗口"""
        try:
            self.window = self.app.window(title=title)
            return self.window
        except ElementNotFoundError:
            print(f"未找到窗口: {title}")
            return None
    
    def click_button(self, button_name):
        """点击按钮"""
        try:
            self.window[button_name].click()
            return True
        except Exception as e:
            print(f"点击失败: {e}")
            return False
    
    def input_text(self, control_name, text):
        """输入文本"""
        try:
            self.window[control_name].set_text(text)
            return True
        except Exception as e:
            print(f"输入失败: {e}")
            return False
    
    def get_text(self, control_name):
        """获取文本"""
        try:
            return self.window[control_name].window_text()
        except Exception as e:
            print(f"获取文本失败: {e}")
            return None
    
    def close_window(self):
        """关闭窗口"""
        try:
            if self.window:
                self.window.close()
            return True
        except Exception as e:
            print(f"关闭失败: {e}")
            return False
    
    def double_click_desktop_icon(self, icon_name):
        """双击桌面图标"""
        try:
            desktop = Desktop(backend="uia")
            icon = desktop.window(title=icon_name, control_type="ListItem")
            icon.double_click_input()
            return True
        except Exception as e:
            print(f"双击图标失败: {e}")
            return False
    
    def click_at_position(self, x, y, clicks=1, button='left'):
        """在指定坐标点击"""
        try:
            if clicks == 2:
                pyautogui.doubleClick(x, y, button=button)
            else:
                pyautogui.click(x, y, clicks=clicks, button=button)
            return True
        except Exception as e:
            print(f"点击坐标失败: {e}")
            return False
    
    def find_and_click_image(self, image_path, confidence=0.8):
        """查找并点击图像"""
        try:
            location = pyautogui.locateOnScreen(image_path, confidence=confidence)
            if location:
                pyautogui.click(pyautogui.center(location))
                return True
            return False
        except Exception as e:
            print(f"查找图像失败: {e}")
            return False
    
    def send_keys(self, keys):
        """发送键盘按键"""
        try:
            pyautogui.press(keys)
            return True
        except Exception as e:
            print(f"发送按键失败: {e}")
            return False
    
    def type_text(self, text, interval=0.1):
        """输入文本（使用 pyautogui.write 支持中文）"""
        try:
            pyautogui.write(text, interval=interval)
            return True
        except Exception as e:
            print(f"输入文本失败: {e}")
            return False
    
    def screenshot(self, save_path=None):
        """截屏"""
        try:
            screenshot = pyautogui.screenshot()
            if save_path:
                screenshot.save(save_path)
            return screenshot
        except Exception as e:
            print(f"截屏失败: {e}")
            return None
    
    def run_program(self, program_path, wait_time=2):
        """运行程序"""
        try:
            os.startfile(program_path)
            time.sleep(wait_time)
            return True
        except Exception as e:
            print(f"运行程序失败: {e}")
            return False
    
    def get_window_list(self):
        """获取所有窗口列表"""
        try:
            desktop = Desktop(backend="uia")
            windows = desktop.windows()
            return [w.window_text() for w in windows if w.window_text()]
        except Exception as e:
            print(f"获取窗口列表失败: {e}")
            return []
    
    def get_active_window_title(self):
        """获取当前活动窗口标题"""
        try:
            import win32gui
            hwnd = win32gui.GetForegroundWindow()
            return win32gui.GetWindowText(hwnd)
        except:
            # 备用方案
            try:
                desktop = Desktop(backend="uia")
                return desktop.top_window().window_text()
            except Exception as e:
                print(f"获取活动窗口失败: {e}")
                return None
    
    def wait_for_window(self, title_keyword, timeout=10):
        """等待指定窗口出现"""
        start_time = time.time()
        while time.time() - start_time < timeout:
            active_title = self.get_active_window_title()
            if active_title and title_keyword.lower() in active_title.lower():
                return True
            time.sleep(0.5)
        return False
    
    def focus_window(self, title_keyword):
        """聚焦到指定窗口"""
        try:
            desktop = Desktop(backend="uia")
            windows = desktop.windows()
            for window in windows:
                if title_keyword.lower() in window.window_text().lower():
                    window.set_focus()
                    return True
            return False
        except Exception as e:
            print(f"聚焦窗口失败: {e}")
            return False
    
    # 浏览器操作功能
    def start_browser(self, browser_type="chrome", headless=False):
        """启动浏览器"""
        self.browser = BrowserMCP(browser_type)
        return self.browser.start_browser(headless)
    
    def browser_navigate(self, url):
        """浏览器导航"""
        return self.browser.navigate(url) if self.browser else False
    
    def browser_click(self, by, value, timeout=10):
        """浏览器点击元素"""
        return self.browser.click_element(by, value, timeout) if self.browser else False
    
    def browser_input(self, by, value, text, timeout=10):
        """浏览器输入文本"""
        return self.browser.input_text(by, value, text, timeout) if self.browser else False
    
    def browser_get_text(self, by, value, timeout=10):
        """浏览器获取文本"""
        return self.browser.get_text(by, value, timeout) if self.browser else None
    
    def browser_screenshot(self, save_path):
        """浏览器截屏"""
        return self.browser.take_screenshot(save_path) if self.browser else False
    
    def close_browser(self):
        """关闭浏览器"""
        return self.browser.close_browser() if self.browser else False
    
    def browser_save_login(self, site_name, username, password, login_url=None):
        """保存登录信息"""
        if self.browser:
            self.browser.save_login_info(site_name, username, password, login_url)
            return True
        return False
    
    def browser_auto_login(self, site_name, username_selector, password_selector, submit_selector):
        """自动登录"""
        return self.browser.auto_login(site_name, username_selector, password_selector, submit_selector) if self.browser else False
    
    def browser_search(self, search_url, search_input_selector, search_text, result_selector, max_results=10):
        """搜索并获取结果"""
        return self.browser.search_and_get_results(search_url, search_input_selector, search_text, result_selector, max_results) if self.browser else []
    
    def browser_type_at_cursor(self, text):
        """在浏览器当前光标位置输入"""
        return self.browser.type_at_cursor(text) if self.browser else False
    
    def browser_click_position(self, x, y):
        """点击浏览器页面指定位置"""
        return self.browser.click_page_position(x, y) if self.browser else False
